<template>
	<!-- 排行榜页面容器 -->
	<view class="rank-page">
		<!-- 头部一级导航 -->
		<view class="rank-header">
			<scroll-view class="rank-scroll" scroll-x="true" :scroll-left="scrollTop" @scroll="handleTopScroll">
				<view v-for="(item, index) in primaryListData" :key="index" class="rank-item"
					:class="{ active: activePrimaryTab === index }" @tap="handlePrimaryTabChange(index)">
					{{ item.name }}
				</view>
			</scroll-view>
		</view>

		<!-- 二级导航和内容 -->
		<view class="rank-content">
			<swiper easing-function="linear" class="rank-swiper" @change="handleSwiperChange"
				:current="activePrimaryTab">
				<swiper-item class="rank-swiper-item" v-for="(tab, index) in primaryListData" :key="index">
					<view class="rank-container">
						<!-- 二级导航 -->
						<scroll-view class="sub-rank-scroll">
							<view v-for="(subItem, subIndex) in secondaryListData" :key="subIndex" class="sub-rank-item"
								:class="{ active: activeSecondaryTab === subIndex }"
								@tap="handleSecondaryTabChange(subIndex)">
								{{ subItem.name }}
							</view>
						</scroll-view>
						<!-- 排行榜对应的书本 -->
						<scroll-view class="book-list-scroll" scroll-y @scrolltolower="handleScrollToLower"
							scroll-top="scrollTopBook" show-scrollbar="false">
							<uni-list>
								<uni-list-item v-for="(book, bookIndex) in bookListData" :key="bookIndex"
									:clickable="true" @click="handleBookItemClick(book.id)" class="book-item">
									<template v-slot:header class="book-item-header">
										<view class="book-rank" :class="{ 'book-rank-top': isTopRank(bookIndex) }">
											{{ book.rank }}
										</view>
										<image :src="`${baseURL}${book.image}`" class="book-cover" mode="aspectFill" />
									</template>
									<template v-slot:body class="book-item-body">
										<!-- 名称 -->
										<text class="book-name">{{ book.name }}</text>
										<!-- 扩展信息 -->
										<view class="book-meta">
											<text class="book-tag">{{ book.tagOne }} ·</text>
											<text
												class="book-status">{{queryStatusOptions.find(item => item.id === book.status)?.name}}
												·</text>
											<text class="book-hot">{{ book.hot }}热度</text>
										</view>
									</template>
								</uni-list-item>
							</uni-list>
						</scroll-view>
					</view>
				</swiper-item>
			</swiper>
		</view>
	</view>
</template>
<script lang="ts" setup>
	import { commonPageQueryData } from '@/services/global';
	import { queryAllRankListAPI, pageBooksByRankAPI } from '@/services/rank';
	import { BookItem } from '../../types/book';
	import { PageParams } from '../../types/global';
	import { RankItem } from '../../types/rank';
	import { onShow } from '@dcloudio/uni-app';
	import { ref } from 'vue';
	import { baseURL, queryStatusOptions } from '@/utils/config';

	/**
	 * 一级排行榜当前选中索引
	 */
	const activePrimaryTab = ref<number>(0);
	/**
	 * 二级排行榜当前选中索引
	 */
	const activeSecondaryTab = ref<number>(0);

	/**
	 * 一级排行榜数据
	 */
	const primaryListData = ref<RankItem[]>([]);
	/**
	 * 二级排行榜数据
	 */
	const secondaryListData = ref<RankItem[]>([]);
	/**
	 * 书籍数据列表
	 */
	const bookListData = ref<BookItem[]>([]);
	/**
	 * 是否正在加载书籍数据
	 */
	const isLoadingQueryBook = ref(false);
	/**
	 * 书本区域滚动位置
	 */
	const scrollTopBook = ref(0);
	/**
	 * 是否加载完成
	 */
	const finish = ref(false);
	/**
	 * 是否正在加载
	 */
	const isLoading = ref(true);
	/**
	 * 一级分类左右滑动距离
	 */
	const scrollTop = ref(0);

	/**
	 * 分页参数
	 */
	const pageParams : Required<PageParams> = {
		current: 1,
		size: 8
	};

	/**
	 * 查询参数
	 */
	const queryParams = ref<{
		parentRankId : number;
		rankId : number;
	}>({
		parentRankId: 0,
		rankId: 0
	});

	/**
	 * 页面加载时调用
	 */
	onShow(async () => {
		isLoading.value = true;
		// 查询所有排行榜
		await fetchAllRankList();

		// 延迟加载
		setTimeout(() => {
			handlePrimaryTabChange(activePrimaryTab.value);
			isLoading.value = false;
		}, 500);
	});

	/**
	 * 判断是否为前三名
	 * @param bookIndex 书籍索引
	 * @returns 是否为前三名
	 */
	const isTopRank = (bookIndex : number) : boolean => {
		return bookIndex === 0 || bookIndex === 1 || bookIndex === 2;
	};

	/**
	 * 查询所有排行榜数据
	 */
	const fetchAllRankList = async () => {
		queryAllRankListAPI().then(res => {
			primaryListData.value = res.data;
		});
	};

	/**
	 * 处理swiper切换事件
	 * @param e 切换事件对象
	 */
	const handleSwiperChange = (e : any) => {
		// 避免重复触发
		if (e.detail.current === activePrimaryTab.value) {
			return;
		}

		// 计算一级榜单移动距离
		handleTopScroll(e.detail.current);
		// 处理一级排行榜切换
		handlePrimaryTabChange(e.detail.current);
	};

	/**
	 * 处理一级排行榜切换
	 * @param index 一级排行榜索引
	 */
	const handlePrimaryTabChange = async (index : number) => {
		isLoadingQueryBook.value = true;
		// 设置一级导航选中状态
		activePrimaryTab.value = index;
		// 获取二级导航数据
		secondaryListData.value = primaryListData.value[index].children || [];

		// 重置二级导航选中状态
		activeSecondaryTab.value = 0;

		// 清空数据
		pageParams.current = 1;
		finish.value = false;
		bookListData.value = [];

		// 分页获取书籍数据
		await fetchBookListByRank();
		isLoadingQueryBook.value = false;
	};

	/**
	 * 处理二级排行榜切换
	 * @param index 二级排行榜索引
	 */
	const handleSecondaryTabChange = async (index : number) => {
		// 设置二级导航选中索引
		activeSecondaryTab.value = index;

		// 书本区域滚动到顶部
		scrollTopBook.value = 0;

		// 清空数据
		pageParams.current = 1;
		finish.value = false;
		bookListData.value = [];
		// 分页获取书籍数据
		await fetchBookListByRank();
	};

	/**
	 * 处理滚动到底部事件
	 */
	const handleScrollToLower = async () => {
		if (finish.value || isLoadingQueryBook.value) return;
		pageParams.current++;
		await fetchBookListByRank();
	};

	/**
	 * 处理书籍项点击事件
	 * @param bookId 书籍ID
	 */
	const handleBookItemClick = (bookId : number) => {
		uni.navigateTo({
			url: `/pages/book/index?bookId=${bookId}`
		});
	};

	/**
	 * 根据排行榜查询书籍列表
	 */
	const fetchBookListByRank = async () => {
		queryParams.value.parentRankId = primaryListData.value[activePrimaryTab.value].id;
		queryParams.value.rankId = secondaryListData.value[activeSecondaryTab.value].id;
		// 分页查询书籍列表
		await commonPageQueryData(
			pageBooksByRankAPI,
			bookListData,
			finish,
			isLoading,
			pageParams,
			queryParams
		);
	};

	/**
	 * 处理一级分类滚动
	 * @param current 当前索引
	 */
	const handleTopScroll = (current : number) => {
		// 判断滚动方向
		if (current > activePrimaryTab.value) {
			// 右滑动
			if (current > 0) {
				scrollTop.value = (current - 1) * 100;
			}
		} else {
			// 左滑动
			if (current >= 0) {
				scrollTop.value = Math.max(0, scrollTop.value - 100);
			}
		}
	};
</script>

<style lang="scss">
	/* stylelint-disable */
	/* 排行榜页面容器 */
	.rank-page {
		display: flex;
		flex-direction: column;
		height: 100vh;

		/* 一级排行榜头部 */
		.rank-header {
			height: 30px;

			/* 一级排行榜滚动容器 */
			.rank-scroll {
				width: 100%;
				white-space: nowrap;
				height: 40px;
				background-color: #fafafa;

				/* 一级排行榜项 */
				.rank-item {
					display: inline-block;
					width: 20%;
					height: 32px;
					text-align: center;
					line-height: 32px;

					/* 激活状态 */
					&.active {
						font-weight: bold;
						color: #d97706;
						font-size: 20px;
					}
				}
			}
		}

		/* 排行榜内容容器 */
		.rank-content {
			flex: 1;

			/* 排行榜swiper */
			.rank-swiper {
				height: 100%;

				/* 排行榜swiper项 */
				.rank-swiper-item {
					height: 100%;
					display: flex;
					flex-direction: row;

					/* 排行榜容器 */
					.rank-container {
						display: flex;
						width: 100%;

						/* 二级排行榜滚动容器 */
						.sub-rank-scroll {
							width: 130rpx;
							background-color: #fafafa;

							/* 二级排行榜项 */
							.sub-rank-item {
								height: 96rpx;
								display: flex;
								align-items: center;
								justify-content: center;
								font-size: 26rpx;
								position: relative;

								/* 激活状态 */
								&.active {
									font-weight: bold;
									color: #d97706;
								}
							}
						}

						/* 书籍列表滚动容器 */
						.book-list-scroll {
							flex: 1;
							padding: 20rpx;

							/* 书籍项 */
							.book-item {
								display: flex;
								flex-direction: row;
								margin-bottom: 20rpx;
								background-color: #f8f8f8;

								.book-item-header {
									flex: 1;
									width: 80px;
									display: flex;
									flex-direction: row;

									/* 书籍排名 */
									.book-rank {
										font-size: 30rpx;
										font-weight: 500;
										color: #999;
										margin-right: 10px;
										display: flex;
										align-items: center;

										/* 书籍排名前三位 */
										&.book-rank-top {
											color: #d6a364;
											font-weight: 600;
										}
									}

									/* 书籍封面 */
									.book-cover {
										width: 40px;
										height: 60px;
										border-radius: 8rpx;
									}
								}

								.book-item-body {
									flex: 3;
									margin-left: 20rpx;
									display: flex;
									flex-direction: column;
									justify-content: center;
									align-items: flex-start;

									/* 书籍名称 */
									.book-name {
										display: block;
										font-size: 30rpx;
										font-weight: 500;
										margin-bottom: 10rpx;
									}

									/* 书籍元信息 */
									.book-meta {
										color: #999;
										font-size: 24rpx;

										.book-tag {
											margin-right: 4rpx;
										}

										.book-status {
											margin: 0 4rpx;
										}

										.book-hot {
											margin-left: 4rpx;
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
</style>